//
//  UEManager.m
//  NewDemo
//
//  Created by hu ping kang on 2018/7/20.
//  Copyright © 2018年 Facebook. All rights reserved.
//
#import "ShareView.h"
#import <AVKit/AVKit.h>
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKExtension/SSEThirdPartyLoginHelper.h>
#import "AlertTool.h"
#import "UEManager.h"
#import "RNTestVC.h"
#import <MapKit/MapKit.h>

@implementation UEManager
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(requestLocation){
  
  CLLocationManager * manager = [[CLLocationManager alloc]init];
  [manager requestWhenInUseAuthorization];
  
}
RCT_EXPORT_METHOD(takePhotos){
  
  if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
      dispatch_async(dispatch_get_main_queue(), ^{
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        UIViewController * vc = [UIApplication sharedApplication].keyWindow.rootViewController;
        [vc presentViewController:picker animated:YES completion:nil];
        
      });
  }else{
    [AlertTool alertMessage:@"当前设备不支持拍照"];
  }
  
}

// 接收传过来的 NSString
RCT_EXPORT_METHOD(addEventOne:(NSString *)url){
  NSLog(@"接收传过来的NSString+NSString: %@", url);
  dispatch_async(dispatch_get_main_queue(), ^{
    RNTestVC * vc = [[RNTestVC alloc]init];
    vc.url = url;
    UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:vc];
    [UIApplication.sharedApplication.keyWindow.rootViewController presentViewController:nav animated:YES completion:nil];
  });
 
}

// weixi
RCT_EXPORT_METHOD(shareToWX:(NSString *)url){
  NSLog(@"接收传过来的NSString+NSString: %@", url);
  dispatch_async(dispatch_get_main_queue(), ^{
    [self shareMsgInfo:url platform:SSDKPlatformSubTypeWechatTimeline success:^{
      [AlertTool alertMessage:@"微信分享成功"];
    } fail:^{
      [AlertTool alertMessage:@"微信分享失败"];
    }];
  });
  
}
// 接收传过来的 NSString
RCT_EXPORT_METHOD(shareMsg:(NSString *)url){
  NSLog(@"%@",url);
  dispatch_async(dispatch_get_main_queue(), ^{
    ShareView * share = [[ShareView alloc]initWithShareProTitle:@"分享到"];
    share.btnClick = ^(NSInteger index) {
      SSDKPlatformType plat = [self getTypeIndex:index];
      [self shareMsgInfo:url platform:plat success:^{
        [AlertTool alertMessage:@"分享成功"];
      } fail:^{
        [AlertTool alertMessage:@"分享成功"];
      }];
    };
    [[UIApplication sharedApplication].keyWindow addSubview:share];
  });
  
}
-(SSDKPlatformType)getTypeIndex:(NSInteger)index{
  switch (index) {
    case 0:
      return SSDKPlatformSubTypeWechatSession;
      break;
    case 1:
      return SSDKPlatformSubTypeWechatTimeline;
      break;
    case 2:
      return SSDKPlatformSubTypeQQFriend;
      break;
    case 3:
      return SSDKPlatformSubTypeQZone;
      break;
    case 4:
      return SSDKPlatformTypeSinaWeibo;
      break;
  }
  return SSDKPlatformSubTypeWechatSession;
}
// 接收传过来的 NSString
RCT_EXPORT_METHOD(shareToQQ:(NSString *)url){
  NSLog(@"接收传过来的NSString+NSString: %@", url);
  dispatch_async(dispatch_get_main_queue(), ^{
    [self shareMsgInfo:url platform:SSDKPlatformTypeQQ success:^{
      [AlertTool alertMessage:@"QQ分享成功"];
    } fail:^{
      [AlertTool alertMessage:@"QQ分享失败"];
    }];
  });
  
}

//直接分享：
-(void)shareMsgInfo:(NSString *)url platform:(SSDKPlatformType)platform success:(void(^)(void))success fail:(void(^)(void))fail{
  //1、创建分享参数
  NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
  [shareParams SSDKSetupShareParamsByText:@"哈哈哈哈"
                                   images:nil
                                      url:[NSURL URLWithString:url]
                                    title:@"RN Share"
                                     type:SSDKContentTypeAuto];
  [ShareSDK share:platform parameters:shareParams onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
    
    switch (state) {
      case SSDKResponseStateSuccess:
        NSLog(@"分享成功");
        success();
        break;
      case SSDKResponseStateFail:
        NSLog(@"分享失败");
        fail();
        break;
      case SSDKResponseStateCancel:
        NSLog(@"用户取消");
        fail();
        break;
      default:
        break;
    }
  }];
  
}

//
RCT_EXPORT_METHOD(getQQInfo){
  dispatch_async(dispatch_get_main_queue(), ^{
    [self getUserInfoSuccess:^(NSArray *array) {
      [[NSNotificationCenter defaultCenter]postNotificationName:@"QQINFO" object:nil userInfo:@{@"iconUrl":array.firstObject,@"nickName":array.lastObject}];
    } fail:^{
      [AlertTool alertMessage:@"授权失败"];
    }];
  });
  
}
-(void)getUserInfoSuccess:(void(^)(NSArray *))success fail:(void(^)())fail{
  
  [SSEThirdPartyLoginHelper loginByPlatform:SSDKPlatformTypeQQ
                                 onUserSync:^(SSDKUser *user, SSEUserAssociateHandler associateHandler) {
                                   associateHandler (user.uid, user, user);
                                   //授权或者登录成功了，才会回调到这里；
                                   success(@[user.icon,user.nickname]);
                                 }
                              onLoginResult:^(SSDKResponseState state, SSEBaseUser *user, NSError *error) {
                                
                                if (state != SSDKResponseStateSuccess)
                                {
                                  fail(@{});
                                }
                              }];

}
//计算文本的高度：
//RCTResponseSenderBlock: 接收多个参数的回调函数
//RCTResponseErrorBlock:  接收错误参数的回调函数
//RCTPromiseRejectBlock:  处理Promise Reject
//RCTPromiseResolveBlock: 处理Promise Resolve
RCT_EXPORT_METHOD(getTextHeight:(NSString *)text callback:(RCTResponseSenderBlock)callback){
  //
  NSLog(@"%@",text);
  CGFloat height = [self calculateRowHeight:text];
  callback(@[@(height)]);
  
  
}


/**
 @method 获取指定宽度情况ixa，字符串value的高度
 @param value 待计算的字符串
 @param fontSize 字体的大小
 @param andWidth 限制字符串显示区域的宽度
 @result float 返回的高度
 */
- (CGFloat)calculateRowHeight:(NSString *)string{
  NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17.0f]};//指定字号
  CGRect rect = [string boundingRectWithSize:CGSizeMake([[UIScreen mainScreen]bounds].size.width - 20, 0)/*计算高度要先指定宽度*/ options:NSStringDrawingUsesLineFragmentOrigin |
                 NSStringDrawingUsesFontLeading attributes:dic context:nil];
  return rect.size.height;
}



@end
